package org.news.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.news.dao.BaseDao;
import org.news.dao.UserDao;
import org.news.entity.User;

public class UserDaoImpl extends BaseDao implements UserDao {
	
	public User findUser(String uname, String password) {
		Connection con=getConnection();
		PreparedStatement ps=null;
		User user=null;
		String sql = "select * from NEWS_USERS where uname=? and upwd=?";
		try{			
			ps = con.prepareStatement(sql);			
			ps.setString(1,uname);
			ps.setString(2,password);
			rs = ps.executeQuery();	
			if(rs.next()){
				user= new User();
				user.setUid(rs.getString("uid"));
				user.setUname(uname);
				user.setUpwd(password);
			}
		}catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(con, ps,  rs);
		}		
		return user;
	}

	@Override
	public boolean checkName(String uname) {
		boolean flag = false;
		Connection con=getConnection();
		PreparedStatement ps=null;
		String sql = "select * from NEWS_USERS where uname=?";
		try{			
			ps = con.prepareStatement(sql);			
			ps.setString(1,uname);
			rs = ps.executeQuery();	
			if(rs.next()){
				flag=true;
			}
		}catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(con, ps,  rs);
		}		
		return flag;
	}
	
	@Override
	public List<String> findByName(String name) {
		List<String> list = new ArrayList<>();
		Connection con=getConnection();
		PreparedStatement stmt=null;
		ResultSet rs = null;
		String sql="select uname from NEWS_USERS where uname like ? LIMIT 0,5;";
		try {
			stmt = con.prepareStatement(sql);
			stmt.setString(1, "%"+name+"%");
			rs  =stmt.executeQuery();
			while(rs.next()){
				list.add(rs.getString("uname").trim());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			super.closeAll(con, stmt, rs);
		}
		return list;
	}
}
